package com.easyaop.asm.bytecode;

import com.easyaop.api.join.JoinPoint;
import org.objectweb.asm.Type;

import java.lang.reflect.Method;

public final class Context {

    private static int size;
    private static JoinPoint[] joinPoints = new JoinPoint[100];

    public static JoinPoint getJoinPoint(int pos) {
        return joinPoints[pos];
    }

    public synchronized static int index(ClassLoader loader,String className,String method,String desc) {

        String signature = className + "#" + method+ "" + desc;


        JoinPoint jp = new JoinPoint(loader, signature);

        JoinPoint[] _joinPoints = joinPoints;
        final int _size = size;
        for (int i = 0; i < _size; i++) {
            JoinPoint j = _joinPoints[i];

            if (j.getSignature().equals(signature)
                    && j.getClassLoader().equals(loader)) {
                return i;
            }
        }

        if (_size == joinPoints.length) {
            // 扩容
            _joinPoints= new JoinPoint[_size + 100];
            System.arraycopy(joinPoints, 0, _joinPoints, 0, _size);
            joinPoints = _joinPoints;
        }
        _joinPoints[_size] = jp;
        return size++;
    }
    public synchronized static int index(Method method) {

        ClassLoader classLoader = method.getDeclaringClass().getClassLoader();
        String descriptor = Type.getMethodDescriptor(method);

        return index(classLoader,method.getDeclaringClass().getName(), method.getName(), descriptor);

    }
}
